﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ProgNetComponentsDx.Enums;
using DevExpress.XtraScheduler;
using BuildHelper.Scheduler.DataSets;
using DevExpress.Utils.Menu;

namespace BuildHelper.Scheduler
{
    public partial class SchedulerForm : XtraForm
    {
        public SchedulerForm()
        {
            InitializeComponent();
            zadaniaDataSet.WRK_ZADANIA.ColumnChanging += new DataColumnChangeEventHandler(WRK_ZADANIA_ColumnChanging);
            if (!this.IsDesignMode() && ProgNetComponents.Data.SqlCe.SqlCeDataManager.GlobalConnectionString.IsNotNull())
            {
                for (int i = 1; i < this.schedulerStorage1.Appointments.Labels.Count; i++)
                {
                    this.schedulerStorage1.Appointments.Labels[i].DisplayName = "Label " + i;
                    this.schedulerStorage1.Appointments.Labels[i].MenuCaption = "Label " + i;
                }
                this.schedulerStorage1.Appointments.Labels[0].DisplayName = "Brak";
                this.schedulerStorage1.Appointments.Labels[0].MenuCaption = "Brak";
                foreach (Zadanie z in Zadanie.Zadania)
                {
                    if (z.Label != null)
                        this.schedulerStorage1.Appointments.Labels.Add(z.Label);
                }
                selectDataProvider1.FillDataSet();
            }
        }

        void WRK_ZADANIA_ColumnChanging(object sender, DataColumnChangeEventArgs e)
        {
            if (e.Column.ColumnName == "WRK_ZAD_ID" && e.Row.CanRead())
            {
                if (e.ProposedValue.IsNull())
                    e.ProposedValue = e.Row["WRK_ZAD_ID"];
            }
        }

        private string ValidationMessage;

        protected virtual bool Save()
        {
            bool result = selectDataProvider1.UpdateDataSet(); 
            return result;
        }
        protected virtual void FinishEdit()
        {
            //if (this.ActiveControl != null && this.ActiveControl is BaseEdit)
            //    (this.ActiveControl as BaseEdit).SendKey(new KeyEventArgs(Keys.Enter));
            this.SelectNextControl(this.ActiveControl, true, true, true, true);
            this.BindingContext.EndCurrentEdit();
        }
        protected virtual void SaveClick()
        {
            if (ValidateAll())
            {
                if (Save())
                {
                    modeProvider1.CurrentMode = FormMode.Read;
                    changeDetectorProvider1.ResetAll();
                }
                else
                {
                    this.ShowDxErrorDialog("Błąd zapisu!");
                }
            }
            else
            {
                if (ValidationMessage.IsNull())
                    ValidationMessage = "Błąd validacji.";

                this.ShowDxErrorDialog(ValidationMessage);
            }
        }

        protected virtual void EditClick()
        {

            if (modeProvider1.CurrentMode == FormMode.Read)
            {
                modeProvider1.CurrentMode = FormMode.Edit;
            }
            else
            {
                if (changeDetectorProvider1.HasChanges)
                {
                    DialogResult res = this.ShowDxYNCQuestionDialog("Zapisać zmiany?");
                    if (res == System.Windows.Forms.DialogResult.No)
                    {
                        zadaniaDataSet.RejectChanges();
                        changeDetectorProvider1.ResetAll();
                        modeProvider1.CurrentMode = FormMode.Read;
                    }
                    else if (res == System.Windows.Forms.DialogResult.Yes)
                    {
                        SaveClick();
                    }
                }
                else
                {
                    modeProvider1.CurrentMode = FormMode.Read;
                }
            }
        }

        protected virtual void RefreshClick()
        {
            selectDataProvider1.FillDataSet();
            changeDetectorProvider1.ResetAll();
        }
        protected virtual bool ValidateAll()
        {
            bool result = true;
            ValidationMessage = "";
            //dxErrorProvider1.ClearErrors();
            //result = modeProvider1.ValidateRequiredEdits(ref ValidationMessage);
            //if (!result)
            //{
            //    IList<Control> controls = dxErrorProvider1.GetControlsWithError();
            //    if (controls.Count > 0)
            //    {
            //        controls[0].Focus();
            //        NavigateToControl(controls[0]);
            //    }
            //}
            return result;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            
        }
        protected override void OnClosing(CancelEventArgs e)
        {
            if (!Program.IsExit)
            {
                e.Cancel = true;
                Hide();
            }
            base.OnClosing(e);
        }
        protected override void OnVisibleChanged(EventArgs e)
        {
            base.OnVisibleChanged(e);
            if (Visible)
                GoToToday();
        }

        private void GoToToday()
        {
            if (dateNavigator1.Selection.Count > 1)
                this.schedulerControl1.Services.DateTimeNavigation.GoToDate(DateTime.Now.AddDays(-1));
            else
                this.schedulerControl1.Services.DateTimeNavigation.GoToToday();
        }

        private Appointment autoDelApp = null;
        private void schedulerControl1_RemindersFormShowing(object sender, DevExpress.XtraScheduler.RemindersFormEventArgs e)
        {
            e.Handled = true;
            foreach (ReminderAlertNotification a in e.AlertNotifications)
            {
                Zadanie z = Zadanie.Zadania[a.ActualAppointment.CustomFields["WRK_ZAD_ZADANIE"].AsString()];
                if (z != null)
                {
                    a.Handled = true;
                    a.Reminder.Dismiss();
                    List<string> list = new List<string>();
                    for(int i=1;i<Zadanie.MAX_PARAMS;i++)
                        list.Add(a.ActualAppointment.CustomFields["WRK_ZAD_PARAM"+i].AsString());
                    z.Action.DynamicInvoke(z.GetRealParams(null, list.ToArray()));
                    autoDelApp = a.ActualAppointment;
                    schedulerControl1.DeleteAppointment(a.ActualAppointment);
                }
            }
            Save();
        }

        private void schedulerControl1_EditAppointmentFormShowing(object sender, DevExpress.XtraScheduler.AppointmentFormEventArgs e)
        {
            e.Handled = true;
            ActionAppointmentForm app = new ActionAppointmentForm(schedulerControl1, e.Appointment, e.OpenRecurrenceForm);
            e.DialogResult = app.ShowDialog(this);
        }

        private void schedulerControl1_EditRecurrentAppointmentFormShowing(object sender, DevExpress.XtraScheduler.EditRecurrentAppointmentFormEventArgs e)
        {
            e.Handled = true;
            ActionAppointmentForm app = new ActionAppointmentForm(schedulerControl1, e.Appointment, e.OpenRecurrenceForm);
            e.DialogResult = app.ShowDialog(this);
        }

        private void schedulerStorage1_ReminderAlert(object sender, DevExpress.XtraScheduler.ReminderEventArgs e)
        {
            
        }

        private void schedulerStorage1_Changed(object sender, DevExpress.XtraScheduler.PersistentObjectsEventArgs e)
        {
            //changeDetectorProvider1.SetModified();
           bool res = Save();
        }

        private void bbiOdswiez_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RefreshClick();
        }

        private void bbiZapisz_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SaveClick();
        }

        private void bbiEdytuj_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            EditClick();
        }

        private void schedulerControl1_PreparePopupMenu(object sender, PreparePopupMenuEventArgs e)
        {
            SchedulerMenuItem item = e.Menu.GetMenuItemById(SchedulerMenuItemId.GotoDate);
            if (item != null)
                item.Caption = "Idź do daty";
            item = e.Menu.GetMenuItemById(SchedulerMenuItemId.GotoToday);
            if (item != null)
                item.Caption = "Idź do dziś";
            item = e.Menu.GetMenuItemById(SchedulerMenuItemId.NewAppointment);
            if (item != null)
                item.Caption = "Nowe Zadanie";

            item = e.Menu.GetMenuItemById(SchedulerMenuItemId.NewRecurringAppointment);
            if (item != null)
                item.Caption = "Nowe Zadanie Cykliczne";
            
            List<DXMenuItem> l = new List<DXMenuItem>();

            if (e.Menu != null)
            {
                if (e.Menu.Id == SchedulerMenuItemId.AppointmentMenu )
                {
                    l.AddIfNotExist(e.Menu.GetPopupMenuById(SchedulerMenuItemId.LabelSubMenu));
                    l.AddIfNotExist(e.Menu.GetPopupMenuById(SchedulerMenuItemId.StatusSubMenu));
                }
                else if (e.Menu.Id == SchedulerMenuItemId.DefaultMenu || e.Menu.Id == SchedulerMenuItemId.RulerMenu)
                {
                    l.AddIfNotExist(e.Menu.GetMenuItemById(SchedulerMenuItemId.NewAllDayEvent));
                    l.AddIfNotExist(e.Menu.GetMenuItemById(SchedulerMenuItemId.NewRecurringEvent));
                    l.AddIfNotExist(e.Menu.GetMenuItemById(SchedulerMenuItemId.NewAllDayEvent));
                    if (e.Menu.Id == SchedulerMenuItemId.RulerMenu)
                    {
                        l.AddIfNotExist(e.Menu.GetMenuItemById(SchedulerMenuItemId.CustomizeTimeRuler));
                    }
                }
            }

            foreach (DXMenuItem i in l)
                if (i != null)
                    i.Visible = false;
        }

        private void modeProvider1_CustomGetModes(object sender, ProgNetComponentsDx.Mode.CustomModeSettingsEventArgs e)
        {
            //if (sender == bbiZapisz)
            //{
            //    if (!changeDetectorProvider1.HasChanges)
            //        e.IsReadOnly = true;
            //}
        }

        private void changeDetectorProvider1_ContextChanged(object sender, EventArgs e)
        {
            //modeProvider1.RefreshObject(bbiZapisz);
        }

        private void schedulerControl1_DeleteRecurrentAppointmentFormShowing(object sender, DeleteRecurrentAppointmentFormEventArgs e)
        {
            if (e.Appointment == autoDelApp)
            {
                e.QueryResult = RecurrentAppointmentAction.Occurrence;
                e.Handled = true;
                e.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
        }
    }
}
